<template>
    <div class="app-container">
        <div class="filter-container">
          <el-button v-has="'commTable_add'" class="filter-item"  @click="handleCreate" type="primary" icon="el-icon-plus">新增沟通</el-button>
          <el-button v-has="'commTable_mutilDisable'" class="filter-item" @click="handleBatchInvalid" type="primary" icon="el-icon-circle-close-outline" >{{$t('table.batchInvalid')}}</el-button>
          <el-button v-has="'commTable_export'" class="filter-item" @click="handleExcelExport" type="primary" icon="el-icon-download" >{{$t('table.excelExport')}}</el-button>

          <br/>

                <div class="date_picker">
                    <el-date-picker
                      v-model="listQuery.begDate"
                      type="date"
                      placeholder="开始时间"
                      :picker-options="pickerBeginDateBefore"
                       @change="changeTime"
                      >
                    </el-date-picker> -
                    <el-date-picker
                      v-model="listQuery.endDate"
                      type="date"
                      placeholder="结束时间"
                      :picker-options="pickerBeginDateAfter"
                      >
                    </el-date-picker>
                </div>

                <el-input style="width: 200px;" class="filter-item" placeholder="供应商简称" v-model="listQuery.abbreviation">
                  </el-input>

                <el-select clearable style="width: 120px" class="filter-item" v-model="listQuery.status" :placeholder="$t('沟通状态')" @change="handleFilter">
                    <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key">
                    </el-option>
                  </el-select>

                <el-select clearable style="width: 120px" class="filter-item" v-model="listQuery.objId" :placeholder="$t('咔哒对接人')" @change="handleFilter">
                  <el-option v-for="item in linkManOptions" :key="item.key" :label="item.label" :value="item.key">
                  </el-option>
                </el-select>

                <el-select clearable style="width: 120px" class="filter-item" v-model="listQuery.commGoal" :placeholder="$t('沟通目的')" @change="handleFilter">
                  <el-option v-for="item in commGoalOptions" :key="item.key" :label="item.label" :value="item.key">
                  </el-option>
                </el-select>

                  <el-select clearable style="width: 120px" class="filter-item" v-model="listQuery.commProgress" :placeholder="$t('沟通进度')" @change="handleFilter">
                    <el-option v-for="item in commProgressOptions" :key="item.key" :label="item.label" :value="item.key">
                    </el-option>
                  </el-select>

                  <el-select clearable style="width: 120px" class="filter-item" v-model="listQuery.commDifficulty" :placeholder="$t('沟通难度')" @change="handleFilter">
                    <el-option v-for="item in commDifficultyOptions" :key="item.key" :label="item.label" :value="item.key">
                    </el-option>
                  </el-select>

                  

          <br/>


            <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('table.search')}}</el-button>

            <el-button class="filter-item" type="primary" v-waves icon="el-icon-refresh" @click="restQuery">{{$t('table.reset')}}</el-button>

            <br/>




        </div>


        <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row ref="table"
                style="width: 100%"
                @selection-change="selectionChange">


          <el-table-column type="selection" :selectable='checkboxInit' width="35" reserve-selection="" ></el-table-column>

          <el-table-column align="center" :label="$t('table.showId')" width="65">
                  <template slot-scope="scope">
                    <span>{{scope.row.showId}}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="供应商简称">
                    <template slot-scope="scope">
                        <span>{{scope.row.supplyName}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="沟通时间" width="180px">
                    <template slot-scope="scope">
                        <span>{{scope.row.commTime | $dateConvert("YYYY-MM-DD HH:mm:ss")}}</span>
                    </template>
                </el-table-column>

                <el-table-column align="center" label="沟通状态" width="180px">
                    <template slot-scope="scope">
                        <span>{{scope.row.status | validFilter}}</span>
                    </template>
                </el-table-column>

                <el-table-column align="center" label="沟通方式">
                    <template slot-scope="scope">
                      <el-tag v-for="(item,index) in scope.row.commType.split(',')" type="success" :key="index">{{item | $commTypeFilter}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="沟通目的">
                    <template slot-scope="scope">
                        <span>{{scope.row.commGoal | commGoalFilter}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="沟通进度">
                    <template slot-scope="scope">
                        <span>{{scope.row.commProgress |commProgressFilter}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="沟通难度">
                    <template slot-scope="scope">
                        <span>{{scope.row.commDifficulty |commDifficultyFilter}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="咔哒对接人">
                    <template slot-scope="scope">
                        <span>{{scope.row.objName}}</span>
                    </template>
                </el-table-column>
            <el-table-column align="center" :label="$t('table.actions')" width="250" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button v-has="'commTable_edit'" type="primary" size="mini"  v-show="scope.row.status=='T'" @click="handleUpdate(scope.row)">{{$t('table.edit')}}</el-button>
                    <el-button v-has="'commTable_info'" type="info" size="mini" @click="handleInfo(scope.row)">{{$t('table.info')}}</el-button>
                    <el-button v-has="'commTable_disable'" size="mini" type="danger"  v-show="scope.row.status=='T'" @click="handleInvalid(scope.row,'deleted')">{{$t('table.invalid')}}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination background @current-change="handleCurrentChange" :current-page="page.page" :page-size="page.limit" layout="total, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>



    </div>
</template>

<script>
    import { fetchList, fetchLinkManList, invalidCommunication, batchInvalid } from '@/api/communication/communication'
    import waves from '@/directive/waves' // 水波纹指令
    import { parseTime } from '@/utils'
    import moment from 'moment/moment'
    import store from '@/store'

    // const begin = moment().add(-2, 'month').format('YYYY-MM-DD')
    // const now = moment().format('YYYY-MM-DD')

    export default {
      name: 'complexTable',
      directives: {
        waves
      },
      data() {
        return {
          tableKey: 0,
          list: null,
          total: null,
          listLoading: true,
          page: {
            page: 1,
            limit: 50,
            sort: ''
          },
          listQuery: {
            supplyId: undefined,
            supplyName: undefined,
            linkNameId: undefined,
            linkName: undefined,
            commTime: undefined,
            commType: undefined,
            commGoal: undefined,
            commProgress: undefined,
            commDifficulty: undefined,
            objId: undefined,
            objName: undefined,
            commContext: undefined,
            commResult: undefined,
            begDate: '',
            endDate: '',
            // begDate: begin,
            // endDate: now,
            'page.limit': 50,
            'page.sort': 'SHOW_ID',
            'page.order': 'DESC'
          },
          commGoalOptions: [{ label: '接洽', key: 'CONTACT' }, { label: '内容引入', key: 'CONTENT' }, { label: '内容输入', key: 'INPUT' }, { label: '商务交流', key: 'BUSINESS' }],
          commProgressOptions: [{ label: '待完成', key: 'WAIT' }, { label: '已完成', key: 'FINISH' }],
          commDifficultyOptions: [{ label: '一星', key: 'ONE' }, { label: '二星', key: 'TWO' }, { label: '三星', key: 'THREE' }, { label: '四星', key: 'FOUR' }, { label: '五星', key: 'FIVE' }],
          linkManOptions: [],
          statusOptions: [{ label: '已生效', key: 'T' }, { label: '已失效', key: 'F' }],
          temp: {
            supplyId: '',
            supplyName: '',
            linkNameId: '',
            linkName: '',
            commTime: '',
            commType: '',
            commGoal: '',
            commProgress: '',
            commDifficulty: '',
            objId: '',
            objName: '',
            commContext: '',
            commResult: ''
          },
          downloadLoading: false,
          // pickerBeginDateBefore: {
          //   disabledDate: (time) => {
          //     const beginDateVal = this.listQuery.begDate
          //     if (beginDateVal) {
          //       return time.getTime() > beginDateVal
          //     }
          //   }
          // },
          pickerBeginDateAfter: {
            disabledDate: (time) => {
              const beginDateVal = this.listQuery.begDate
              if (beginDateVal) {
                return time.getTime() < beginDateVal
              }
            }
          }
        }
      },
      filters: {
        commGoalFilter(commGoal) {
          const commGoalMap = {
            GEREN: '个人',
            CONTACT: '接洽',
            CONTENT: '内容引入',
            INPUT: '内容输入',
            BUSINESS: '商务交流'
          }
          return commGoalMap[commGoal]
        },
        commProgressFilter(commProgress) {
          const commProgressMap = {
            WAIT: '待完成',
            FINISH: '已完成'
          }
          return commProgressMap[commProgress]
        },
        commDifficultyFilter(commDifficulty) {
          const commDifficultyMap = {
            ONE: '一星',
            TWO: '二星',
            THREE: '三星',
            FOUR: '四星',
            FIVE: '五星'
          }
          return commDifficultyMap[commDifficulty]
        },
        validFilter(status) {
          const statusMap = {
            T: '已生效',
            F: '已失效'
          }
          return statusMap[status]
        }
      },
      created() {
        this.getList()
        this.getLinkManList()
      },
      methods: {
        getList() {
          this.listLoading = true
          fetchList(this.listQuery).then(response => {
            this.list = response.content.list
            this.total = response.content.total
            this.listLoading = false
          })
        },
        getLinkManList() {
          this.listLoading = true
          fetchLinkManList().then(response => {
            if (response.success) {
              for (var a = 0; a < response.content.length; a++) {
                var aa = { label: response.content[a].userName, key: response.content[a].id }
                this.linkManOptions.push(aa)
              }
            }
          })
        },
        // 搜索按钮
        handleFilter() {
          this.listQuery.page = 1
          this.getList()
        },
        // 跳转页数
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.getList()
        },
        // 详情
        handleInfo(row) {
          this.$router.push({ name: 'commInfo', query: { id: row.id, opt: 'info' }})
        },
        resetTemp() {
          this.temp = {
            supplyId: '',
            supplyName: '',
            linkNameId: '',
            linkName: '',
            commTime: '',
            commType: '',
            commGoal: '',
            commProgress: '',
            commDifficulty: '',
            objId: '',
            objName: '',
            commContext: '',
            commResult: ''
          }
        },
        //
        handleCreate() {
          this.$router.push({ name: 'commAdd' })
        },
        // 更新页面
        handleUpdate(row) {
          this.$router.push({ name: 'commEdit', query: { id: row.id }})
        },
        // 失效操作
        handleInvalid(row) {
          this.$confirm('失效后，该条数据不可操作，确认失效?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then((response) => {
            // 调用删除接口
            var p = { id: row.id }
            invalidCommunication(p).then(response => {
              if (response.success) {
                this.getList()
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
          })
        },
        formatJson(filterVal, jsonData) {
          return jsonData.map(v => filterVal.map(j => {
            if (j === 'timestamp') {
              return parseTime(v[j])
            } else {
              return v[j]
            }
          }))
        },
        handleExcelExport() {
          this.$alert('导出需要一定时间,请耐心等待', '导出提示', {
            confirmButtonText: '导出',
            callback: action => {
              if (action === 'cancel') {
                return
              }
              this.$message({
                type: 'info',
                message: '正在导出...'
              })
              var params = ''
              // 时间过滤
              if (this.listQuery.begDate !== '') {
                this.listQuery.begDate = moment(this.listQuery.begDate).format('YYYY-MM-DD')
                if (this.listQuery.begDate === 'Invalid date') {
                  this.listQuery.begDate = ''
                }
              }
              if (this.listQuery.endDate !== '') {
                this.listQuery.endDate = moment(this.listQuery.endDate).format('YYYY-MM-DD')
                if (this.listQuery.endDate === 'Invalid date') {
                  this.listQuery.endDate = ''
                }
              }
              for (const field in this.listQuery) {
                const val = this.listQuery[field]
                if (typeof val !== 'undefined' && val !== '') {
                  params += field + '=' + val + '&'
                }
              }
    
              if (!params.endsWith('&')) {
                // 加上token
                params += '&'
              }
              params += 'token=' + store.getters.token
              window.open(process.env.BASE_API + '/communication/exportExcel.do?' + params)
            }
          })
        },
        selectionChange(selects) {
          this.selectIds = ''
          for (var select of selects) {
            this.selectIds += select.id
            this.selectIds += ','
          }
          this.selectIds = this.selectIds.substring(0, this.selectIds.length - 1)
        },
        handleBatchInvalid() {
          // 判断是否选择
          if (!this.selectIds) {
            this.$message({
              type: 'fail',
              message: '请先选择数据，再进行失效操作!'
            })
            return
          }
          // TODO 批量失效
          this.$confirm('失效后，所选数据不可操作，确认失效?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then((response) => {
            // 调用批量失效接口
            var params = { 'invalidIds': this.selectIds }
            batchInvalid(params).then(response => {
              if (response.success) {
                this.getList()
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
              } else {
                this.$message({
                  type: 'fail',
                  message: response.message
                })
              }
            })
            this.$refs.table.clearSelection()
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
          })
        },
        // 初始化页面,批量失效,已失效不允许勾选
        checkboxInit(item) {
          var status = item.status
          if (status === 'T') {
            return 1
          } else {
            return 0
          }
        },
        restQuery() {
          // this.listQuery.begDate = begin
          // this.listQuery.endDate = now
          this.listQuery.begDate = ''
          this.listQuery.endDate = ''
          this.listQuery.objId = ''
          this.listQuery.commGoal = ''
          this.listQuery.commProgress = ''
          this.listQuery.commDifficulty = ''
          this.listQuery.abbreviation = ''
          this.listQuery.status = ''
          this.getList()
        },
        // 选择开始时间，清空结束时间
        changeTime(date) {
          this.listQuery.endDate = ''
          this.pickerBeginDateAfter = {
            disabledDate(time) { // 开始时间-结束时间
              return (time.getTime() < new Date(date).getTime())
            }
          }
        }

      }
    }
</script>

<style scoped>
  .date_picker {
   display: inline-block;
  }
  .filter-container .filter-item {
    display: inline-block;
    vertical-align: unset;
  }


</style>
